#ifndef TIMER_H_
#define TIMER_H_

#include "netlib/base/atomic.h"
#include "netlib/base/noncopyable.h"
#include "netlib/base/time_stamp.h"
#include "netlib/net/call_backs.h"

namespace netlib::net {

class Timer : NonCopyable {
public:
	Timer(TimerCallback cb, Timestamp when, double interval) :
	    kCallback(std::move(cb)), expiration_(when), kInterval(interval), kRepeat(interval > 0.0),
	    kSequence(s_num_created.IncrementAndGet()) {}

	void Run() const { kCallback(); }

	Timestamp Expiration() const { return expiration_; }
	bool Repeat() const { return kRepeat; }
	int64_t Sequence() const { return kSequence; }

	void Restart(Timestamp now) {
		if (kRepeat) {
			expiration_ = AddTime(now, kInterval);
		} else {
			expiration_ = Timestamp::Invalid();
		}
	}

	static int64_t NumCreated() { return s_num_created.Get(); }

private:
	const TimerCallback kCallback;
	Timestamp expiration_;
	const double kInterval;
	const bool kRepeat;
	const int64_t kSequence;

	static AtomicInt64 s_num_created;
};

} // namespace netlib::net

#endif // TIMER_H_